package com.tbit.main.controller;

import com.tbit.main.common.JsonResult;
import com.tbit.main.constant.OrderCumConstant;
import com.tbit.main.constant.UserConstant;
import com.tbit.main.pojo.*;
import com.tbit.main.service.*;
import com.tbit.main.util.DateTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

/**
 * 品牌数据统计
 *
 * @author Leon
 * 2020年6月23日 下午5:12:33
 */
@RestController
@RequestMapping("/brandSta")
public class BrandStaController {
    /**
     * 金额格式化
     */
    private DecimalFormat df = new DecimalFormat("0.00");
    @Autowired
    private MachineService machineService;
    @Autowired
    private UserService userService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RideLogService rideLogService;
    @Autowired
    private MemberLogService memberLogService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private OrderCumStaService orderCumStaService;
    @Autowired
    private VipLogService vipLogService;
    @Autowired
    private NewUserDayStaService newUserDayStaService;
    @Autowired
    private RideOrderDayStaService rideOrderDayStaService;
    @Autowired
    private DepositOrderDayStaService depositOrderDayStaService;
    @Autowired
    private VipCardOrderDayStaService vipCardOrderDayStaService;

    /**
     * 根据代理商统计
     */
    @RequestMapping("/staByAccountId")
    public JsonResult send(String token,
                           @RequestParam(value = "startTime", required = false) String startTime,
                           @RequestParam(value = "endTime", required = false) String endTime
    ) {
        AccountUser accountUser = tokenService.getAccount(token);


        /** 获取运营区域信息 */
        List<Account> accounts = new ArrayList<>();
        // 品牌
        if (accountService.getCountHolderAgent(accountUser.getAccountUserId()) > 0) {
            accounts = accountService.getHolderAgent(accountUser.getAccountUserId());
        } else if ((accountUser.getAccountUserType().equals(UserConstant.ACCOUNT_BRAND) ||
                accountUser.getRole().getRoleLevel().equals(UserConstant.ACCOUNT_BRAND))
                && !accountUser.getAccountUserType().equals(UserConstant.ACCOUNT_FRANCHISEE)
                && !accountUser.getAccountUserType().equals(UserConstant.ACCOUNT_ADOPT)) {
            /** 加载品牌下的所有运营区域 */
            accounts = accountService.getBrandAgent(accountUser.getAccountId());
        }
        // 加盟商
        else if ((accountUser.getAccountUserType().equals(UserConstant.ACCOUNT_AREA) ||
                accountUser.getRole().getRoleLevel().equals(UserConstant.ACCOUNT_AREA))
                && !accountUser.getAccountUserType().equals(UserConstant.ACCOUNT_FRANCHISEE)) {
            /** 加载加盟商下面的所有运营区域 */
            accounts = accountService.getByParentId(accountUser.getAccountId());
        }
        //领养人
        else if (accountUser.getAccountUserType().equals(UserConstant.ACCOUNT_ADOPT)) {
        }
        // 区域运营商、运维管理员、运维人员
        else {
            List<Integer> accountIds = new ArrayList<Integer>();
            accountIds.add(accountUser.getAccountId());
            accounts = accountService.getByAccountIds(accountIds);
        }

        List<Integer> accountIds = new LinkedList<>();
        for (Account account : accounts) {
            accountIds.add(account.getAccountId());
        }

        /**可运营车辆数*/
        //投放
        //List<Machine> machines = machineService.getByAccountIds(accountIds);
        //List<String> machineNO = machines.stream().map(Machine::getMachineNO).collect(Collectors.toList());
        //异常
        //List<MachineAbnormal> machineAbnormals = machineAbnormalService.getByAccountIds(accountIds);
        //List<String> machineNOAbnormal = machineAbnormals.stream().map(MachineAbnormal::getMachineNO).collect(Collectors.toList());
        //缺电

        //List<MachineStatus> machineStatuses = machineStatusService.getSocByAccountIds(accountIds,null);


        Map<String, Object> result = new HashMap<String, Object>();

        /**用户总数
         * */
        Integer userCount = userService.getBrandUserCountByAccountIds(accountIds);
        if (userCount != null) {
            result.put("userCount", userCount);
        }

        /**用户余额
         * */
		/*String userMoneyCount=userService.getUserMoneyCountByAccountId(accountIds);
		if(userMoneyCount!=null){
			result.put("userMoneyCount", userMoneyCount);
		}*/

        /**押金数据
         * */
		/*KVEntity kv=userService.getUserDepositCountByAccountId(accountIds);
		if(kv!=null){
			result.put("depositUserCount", kv.getK());
			result.put("depositMoneyCount", kv.getV());
		}*/

        /**投放车辆总数
         * */
        Integer machineCount = machineService.getCountByBrandByAccountId(accountIds);
        if (machineCount != null) {
            result.put("machineCount", machineCount);
        }

        OrderCumSta orderCumSta = new OrderCumSta();
        OrderCumSta orderCumStaMemberSta = new OrderCumSta();
        OrderCumSta orderCumStaVipSta = new OrderCumSta();
        /**判读是否有时间条件*/
        if (startTime == null) {
            /**骑行订单信息
             * */
            orderCumSta = orderCumStaService.getByAccountIdDateDay(accountIds, OrderCumConstant.QX_ORDER);
            if (orderCumSta.getOrderCount() == null) {
                orderCumSta.setOrderCount(0);
            }
            if (orderCumSta.getOrderMoney() == null) {
                orderCumSta.setOrderMoney((float) 0.00);
            } else {
                orderCumSta.setOrderMoney((float) (orderCumSta.getOrderMoney() / 100));
            }

            /**免押会员信息
             * */
            orderCumStaMemberSta = orderCumStaService.getByAccountIdDateDay(accountIds, OrderCumConstant.MY_ORDER);
            if (orderCumStaMemberSta.getOrderCount() == null) {
                orderCumStaMemberSta.setOrderCount(0);
            }
            if (orderCumStaMemberSta.getOrderMoney() == null) {
                orderCumStaMemberSta.setOrderMoney((float) 0.00);
            } else {
                orderCumStaMemberSta.setOrderMoney((float) orderCumStaMemberSta.getOrderMoney() / 100);
            }

            /**会员卡会员信息
             * */
            orderCumStaVipSta = orderCumStaService.getByAccountIdDateDay(accountIds, OrderCumConstant.VIP_ORDER);
            if (orderCumStaVipSta.getOrderCount() == null) {
                orderCumStaVipSta.setOrderCount(0);
            }
            if (orderCumStaVipSta.getOrderMoney() == null) {
                orderCumStaVipSta.setOrderMoney((float) 0.00);
            } else {
                orderCumStaVipSta.setOrderMoney((float) orderCumStaVipSta.getOrderMoney() / 100);
            }

        } else {

            Map<String, Object> orderCumStaMap = rideOrderDayStaService.getByAccountIds(accountIds, startTime, endTime);
            if (orderCumStaMap != null) {
                orderCumSta.setOrderCount(Integer.parseInt(orderCumStaMap.get("orderCount").toString()));
                orderCumSta.setOrderMoney(Float.parseFloat(orderCumStaMap.get("orderMoney").toString()) / 100);
            }

            Map<String, Object> orderCumStaMemberStaMap = depositOrderDayStaService.getByAccountIds(accountIds, startTime, endTime);
            if (orderCumStaMemberStaMap != null) {
                orderCumStaMemberSta.setOrderCount(Integer.parseInt(orderCumStaMemberStaMap.get("orderCount").toString()));
                orderCumStaMemberSta.setOrderMoney(Float.parseFloat(orderCumStaMemberStaMap.get("orderMoney").toString()) / 100);
            }

            Map<String, Object> orderCumStaVipStaMap = vipCardOrderDayStaService.getByAccountIds(accountIds, startTime, endTime);
            if (orderCumStaVipStaMap != null) {
                orderCumStaVipSta.setOrderCount(Integer.parseInt(orderCumStaVipStaMap.get("orderCount").toString()));
                orderCumStaVipSta.setOrderMoney(Float.parseFloat(orderCumStaVipStaMap.get("orderMoney").toString()) / 100);
            }
        }

        /**判断结束日期是否有当天日期*/
        Map<String, Object> mapRideSta = new HashMap<>();
        Map<String, Object> mapMemberSta = new HashMap<>();
        Map<String, Object> mapVipSta = new HashMap<>();
        /**总里程
         * */
        Integer mileageCount = newUserDayStaService.getByAccountIds(accountIds, startTime, endTime);
        if (endTime == null || endTime.substring(0, 10).equals(DateTimeUtil.getNowTimeYMD())) {

            /**骑行订单信息 当天
             * */
            RideSta rideStaOrderCumSta = rideLogService.staByTimeByAccountIds(accountIds, DateTimeUtil.getNowDateTimeBefore(0) + " 00:00:00", DateTimeUtil.getNowTime());
            if (rideStaOrderCumSta.getOrderCount() == null) {
                rideStaOrderCumSta.setOrderCount(0);
            }
            if (rideStaOrderCumSta.getOrderMoney() == null) {
                rideStaOrderCumSta.setOrderMoney(0.00);
            } else {
                rideStaOrderCumSta.setOrderMoney((double) rideStaOrderCumSta.getOrderMoney() / 100);
            }
            mapRideSta.put("orderCount", orderCumSta.getOrderCount() + rideStaOrderCumSta.getOrderCount());
            mapRideSta.put("orderMoney", (new BigDecimal(String.valueOf(orderCumSta.getOrderMoney())).add(new BigDecimal(String.valueOf(rideStaOrderCumSta.getOrderMoney())))));

            /**免押会员信息 当天
             * */
            MemberSta OrderCumSta = memberLogService.staByTimeByAccountIds(accountIds, DateTimeUtil.getNowDateTimeBefore(0) + " 00:00:00", DateTimeUtil.getNowTime());
            if (OrderCumSta.getMemberOrderCount() == null) {
                OrderCumSta.setMemberOrderCount(0);
            }
            if (OrderCumSta.getMemberOrderMoney() == null) {
                OrderCumSta.setMemberOrderMoney(0.00);
            } else {
                OrderCumSta.setMemberOrderMoney((double) OrderCumSta.getMemberOrderMoney() / 100);
            }
            mapMemberSta.put("orderCount", orderCumStaMemberSta.getOrderCount() + OrderCumSta.getMemberOrderCount());
            mapMemberSta.put("orderMoney", (new BigDecimal(String.valueOf(orderCumStaMemberSta.getOrderMoney())).add(new BigDecimal(String.valueOf(OrderCumSta.getMemberOrderMoney())))));

            /**会员卡会员信息 当天
             * */
            VipSta vipSta = vipLogService.getCountAccountIds(accountIds, DateTimeUtil.getNowDateTimeBefore(0) + " 00:00:00", DateTimeUtil.getNowTime());
            if (vipSta.getVipOrderCount() == null) {
                vipSta.setVipOrderCount(0);
            }
            if (vipSta.getVipOrderMoney() == null) {
                vipSta.setVipOrderMoney(0.00);
            } else {
                vipSta.setVipOrderMoney((double) vipSta.getVipOrderMoney() / 100);
            }
            mapVipSta.put("orderCount", orderCumStaVipSta.getOrderCount() + vipSta.getVipOrderCount());
            mapVipSta.put("orderMoney", (new BigDecimal(String.valueOf(orderCumStaVipSta.getOrderMoney())).add(new BigDecimal(String.valueOf(vipSta.getVipOrderMoney())))));

            /**骑行里程 当天
             * */
            Integer mileageNew = rideLogService.newDayMile(accountIds, DateTimeUtil.getNowDateTimeBefore(0) + " 00:00:00", DateTimeUtil.getNowTime());
            if (mileageNew == null) {
                mileageNew = 0;
            }
            mileageCount = mileageCount + mileageNew;
        } else {

            mapRideSta.put("orderCount", orderCumSta.getOrderCount());
            mapRideSta.put("orderMoney", (new BigDecimal(String.valueOf(orderCumSta.getOrderMoney()))));

            mapMemberSta.put("orderCount", orderCumStaMemberSta.getOrderCount());
            mapMemberSta.put("orderMoney", (new BigDecimal(String.valueOf(orderCumStaMemberSta.getOrderMoney()))));

            mapVipSta.put("orderCount", orderCumStaVipSta.getOrderCount());
            mapVipSta.put("orderMoney", (new BigDecimal(String.valueOf(orderCumStaVipSta.getOrderMoney()))));
        }

        result.put("orderCount", mapRideSta.get("orderCount"));
        if (mapRideSta.get("orderMoney") == null) {
            result.put("orderMoney", 0);
        } else {
            result.put("orderMoney", mapRideSta.get("orderMoney"));
        }

        /**免押会员总数
         * */
        Integer memberUserCount = userService.getDepositUserCountByAccountIds(accountIds, DateTimeUtil.getNowTimeYMD());
        if (memberUserCount != null) {
            result.put("memberUserCount", memberUserCount);
        }

        result.put("memberOrderCount", mapMemberSta.get("orderCount"));
        if (mapMemberSta.get("orderMoney") == null) {
            result.put("memberOrderMoney", "0");
        } else {
            result.put("memberOrderMoney", mapMemberSta.get("orderMoney"));
        }

        /**会员卡用户总数
         * */
        Integer vipUserCount = vipLogService.getByAccountIds(accountIds);
        if (vipUserCount != null) {
            result.put("vipUserCount", vipUserCount);
        }

        result.put("vipOrderCount", mapVipSta.get("orderCount"));
        if (mapVipSta.get("orderMoney") == null) {
            result.put("vipOrderMoney", "0");
        } else {
            result.put("vipOrderMoney", mapVipSta.get("orderMoney"));
        }

        /**总里程*/
        result.put("mileageCount", mileageCount);

        return JsonResult.succ(result);
    }

}